package com.hellobike.haxing.modules.wms.controller;

import com.baomidou.mybatisplus.extension.service.IService;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.vo.LoginUser;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.wms.exception.WmsExportException;
import com.hellobike.haxing.modules.wms.facade.WmsExportFacade;
import com.hellobike.haxing.modules.wms.service.IWarehouseDepartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
public class WmsBaseController<T, S extends IService<T>> extends BaseController<T, S> {

    @Autowired
    private IWarehouseDepartService warehouseDepartService;
    @Autowired
    protected WmsExportFacade wmsExportFacade;



    public LoginUser getSysUser(){
        return (LoginUser) SecurityUtils.getSubject().getPrincipal();
    }

    public Integer getSysUserId(){
        return getSysUser().getId();
    }

    public Long getWarehouseId(){
        Long warehouseId = warehouseDepartService.getWarehouseIdByDepartCode(getSysUser().getOrgCode());
        if( -1L == warehouseId){
            throw new RuntimeException("当前部门未绑定仓库");
        }
        return warehouseId;
    }


    @ExceptionHandler
    public Result<?> exp(HttpServletRequest request, Exception ex) throws Exception {
        log.error("wms request error :"+request.getContextPath(),ex);
        if (ex instanceof NullPointerException) {
            return Result.error("系统异常,请稍后重试！");
        }
        if (ex instanceof WmsExportException) {
            throw ex;
        }
        return Result.error(ex.getMessage());
    }

    protected  <TD> ModelAndView  export(String title, Class<TD> clazz, List<TD> exportList){
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, clazz);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title, "导出人:" + getSysUser().getUsername(), title));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

}
